<?php

namespace app\common\model\xilujob;

use app\common\library\Result;
use think\Db;
use think\Exception;
use think\Hook;
use think\Log;
use think\Model;

class ResumeViewLog extends Model
{
    protected $name = 'xilujob_resume_view_log';

    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = false;

    public function enterpriseinfo() {
        return $this->belongsTo('EnterpriseInfo','company_id','company_id');
    }

    /**
     * 查看简历-只有公司有权限
     * @param int $companyId
     * @param int $resumeId
     * @return
     */
    public static function viewResume($companyId, $resumeId) {
        if(!$companyId || !$resumeId) {
            throw new Exception(__('invalid arguments'));
        }
        Db::startTrans();
        try {
            $record = static::where('company_id',$companyId)->where('resume_id', $resumeId)->find();
            $now = time();
            if(!$record) {
                $record = new static();
                $record->save(['company_id'=>$companyId,'resume_id'=>$resumeId,'view_time'=>$now]);
                Resume::where('id',$resumeId)->failException(true)->update(['view_count'=>Db::raw('view_count+1')]);
                Hook::listen('xilujob_resume_viewed', $record);
            }else {
                //两小时内不重复加
                $data = ['view_time'=>time()];
                if($now>$record->view_time+3600*2) {
                    $data['view_count'] = Db::raw('view_count+1');
                }
                $record->save($data);
            }
            Db::commit();
            return true;
        }catch (\Exception $e) {
            Log::error($e->getMessage()."\n".$e->getTraceAsString());
            throw $e;
        }
    }

}
